﻿using adb;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using System.Linq;
using Z.EntityFramework.Plus;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using System;

namespace PowerStation.Controllers
{
    /// <summary>
    /// 公共资源
    /// </summary>
    public class CommomController : BaseApi<CommomController>
    {

        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="content"></param>
        public CommomController(IHttpContextAccessor content) : base(content)
        {
        }


        /// <summary>
        /// 获取系统类型,类型请参考keyType
        /// </summary>
        /// <param name="keyType">类型,1表示部门,2表示职位,3表示电站类型,4表示建设进度,5表示片区,6表示地区,7传感器类型,8表示权限,9表示电站流域</param>
        /// <returns></returns>
        private async Task<IEnumerable<tKey>> KeyList(int keyType)
        {
            return await this._db.tKey.Where(x => x.keyType == keyType && x.dataState == 0).FromCacheAsync(new MemoryCacheEntryOptions() { 
                AbsoluteExpirationRelativeToNow = System.TimeSpan.FromSeconds(10)
            });
        }



        #region 权限管理

        /// <summary>
        /// 获取权限
        /// </summary>
        /// <param name="parentId">如果传-1,就是获取所有的,0表示顶层</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<List<tKey>>> PermissionList(decimal parentId = -1)
        {
            if (parentId == -1) return ResultApi.ok((await this.KeyList(8)).ToList());
            return ResultApi.ok((await this.KeyList(8)).Where(x=>x.keyParent_keyId_fk == parentId).ToList());
        }


        /// <summary>
        /// 全局键值修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<ResultApi<bool>> KeyModify(tKey model)
        {
            int count = await this._db.tKey.Where(x => x.keyId == model.keyId).UpdateAsync(x => new tKey() {
                keyName = model.keyName,
                keyParent_keyId_fk  = model.keyParent_keyId_fk,
                keyType = model.keyType,
                keyValue = model.keyValue,
                sort = model.sort,
                dataState = model.dataState
            });
            return ResultApi.okOrError<bool>(false, false);
        }



        #endregion


        #region 电站

        /// <summary>
        /// 获取电站类型
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<List<tKey>>> PowerStationTypeList()
        {
            IQueryable<tKey> q = this._db.tKey;
            var result = (await this.KeyList(3)).ToList();
            return ResultApi.ok<List<tKey>>(result, result.Count);
        }
        /// <summary>
        /// 获取电站建设进度
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<List<tKey>>> PowerStationProgressList()
        {
            IQueryable<tKey> q = this._db.tKey;
            var result = (await this.KeyList(4)).ToList();
            return ResultApi.ok<List<tKey>>(result, result.Count);
        }
        #endregion

        #region 地域接口
        /// <summary>
        /// 地域片区接口
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<List<tKey>>> AreaList()
        {
            IQueryable<tKey> q = this._db.tKey;
            var result = (await this.KeyList(5)).ToList();
            return ResultApi.ok<List<tKey>>(result, result.Count);
        }

        /// <summary>
        /// 省-城市-县数据列表
        /// </summary>
        /// <param name="parentId">如果传-1,就是获取所有的,0表示顶层</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<List<tKey>>> regionList(decimal parentId = -1)
        {
            if (parentId == -1) return ResultApi.ok((await this.KeyList(6)).ToList());
            return ResultApi.ok((await this.KeyList(6)).Where(x => x.keyParent_keyId_fk == parentId).ToList());
        }

        /// <summary>
        /// 获取城市
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<List<tKey>>> cityList()
        {
            if(_cityListDic != null)return ResultApi.ok(_cityListDic,_cityListDic.Count);
            var lst = (await this.regionList(-1)).data;
            List<tKey> datas = _cityList(lst, 0);
            _cityListDic = datas;
            return ResultApi.ok<List<tKey>>(datas, datas.Count);
        }
        private static List<tKey> _cityListDic = null;
        private List<tKey> _cityList(List<tKey> keys, long pId) { 
            List<tKey> cl = new List<tKey>();
            var lst = keys.Where(x=>x.keyParent_keyId_fk == pId).ToList();
            foreach (var item in lst)
            {
                var childList = _cityList(keys, item.keyId);
                if (item.keyName.EndsWith("市")) {
                    cl.Add(item);
                }
                foreach (var item2 in childList) {
                    if (item2.keyName.EndsWith("市")) {
                        item2.keyName = item.keyName + item2.keyName;
                        cl.Add(item2);
                    }
                };
            }
            return cl;
        }

        #endregion
        /// <summary>
        /// 获取省
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<List<tKey>>> ShengList()
        {
            var lst = this._db.tKey.Where(x=>x.keyType == 6 && x.keyParent_keyId_fk == 0);
            List<tKey> datas = await lst.ToListAsync();
            _cityListDic = datas;
            return ResultApi.ok<List<tKey>>(datas,datas.Count());
        }
        /// <summary>
        /// 获取市
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<List<tKey>>> ShiList(string ShengMing)
        {
            var lst = this._db.tKey.FirstOrDefault(x=>x.keyType == 6 && x.keyParent_keyId_fk == 0 && x.keyName == ShengMing);
            if (lst == null) return ResultApi.error<List<tKey>>(null, "找不到该省下的所属市数据");
            var slist = await this._db.tKey.Where(x => x.keyParent_keyId_fk == lst.keyId).ToListAsync();
            return ResultApi.ok<List<tKey>>(slist,slist.Count);
        }
        /// <summary>
        /// 获取县
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<List<tKey>>> XianList(string ShiMing)
        {
            var lst = this._db.tKey.FirstOrDefault(x => x.keyType == 6 && x.keyParent_keyId_fk != 0 && x.keyName == ShiMing);
            if (lst == null) return ResultApi.error<List<tKey>>(null, "找不到该市下的所属县数据");
            var slist = await this._db.tKey.Where(x => x.keyParent_keyId_fk == lst.keyId).ToListAsync();
            return ResultApi.ok<List<tKey>>(slist,slist.Count);
        }

        #region 流域

        /// <summary>
        /// 获取流域列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<List<tKey>>> DrainageAreaList()
        {
            IQueryable<tKey> q = this._db.tKey;
            var result = await q.Where(x=>x.keyType == 9).ToListAsync();
            return ResultApi.ok<List<tKey>>(result, result.Count);
        }

        /// <summary>
        /// 新增流域
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultApi<decimal>> DrainageAreaCreate(tKey model)
        {
            model.keyType = 9;
            model.addTime = DateTime.Now;
            model.sort = 0;
            model.keyParent_keyId_fk = 0;
            model.keyValue = "";
            model.dataState = 0;
            model.keyId = 0;
            if (string.IsNullOrWhiteSpace(model.keyName)) return ResultApi.error(decimal.Zero,"流域名称不能为空");
            if (await this._db.tKey.AnyAsync(x=>x.keyType == model.keyType && x.keyName == model.keyName)) return ResultApi.error(decimal.Zero, "流域已经存在,不能新增重复项");
            await this._db.tKey.AddAsync(model);
            await this._db.SaveChangesAsync();
            return ResultApi.okOrError<decimal>(model.keyId > 0, model.keyId);
        }

        /// <summary>
        /// 删除流域
        /// </summary>
        /// <returns></returns>
        [HttpDelete]
        public async Task<ResultApi<bool>> DrainageAreaDeleta(decimal keyId)
        {
            await this._db.tKey.Where(x=>x.keyId == keyId && x.keyType == 9).UpdateAsync(x=>new tKey() { dataState = 1});
            await this._db.SaveChangesAsync();
            return ResultApi.okOrError<bool>(true, true);
        }

        #endregion


        #region 传感器类型

        /// <summary>
        /// 传感器类型
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<IEnumerable<tKey>>> DeviceTypeList()
        {
            var q = await this.KeyList(7);
            return ResultApi.ok<IEnumerable<tKey>>(q);
        }

        #endregion
    }
}
